from flask import Blueprint, request, jsonify
import json
import os
from datetime import datetime

# 创建蓝图
moYanWishers_bp = Blueprint('moYanWishers', __name__)

# 数据文件路径
WISHERS_FILE = os.path.join('/www/wwwroot/moyan.yapei.cool/birthday/data', 'wishes.json')

# 初始化文件
def initialize_wishers_file():
    if not os.path.exists(WISHERS_FILE):
        with open(WISHERS_FILE, 'w', encoding='utf-8') as f:
            json.dump([], f, ensure_ascii=False, indent=2)

# 读取数据
def read_wishers():
    initialize_wishers_file()
    try:
        with open(WISHERS_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    except json.JSONDecodeError:
        return []

# 写入数据
def write_wishers(data):
    with open(WISHERS_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

# 接口：添加愿望者
@moYanWishers_bp.route('/add-wisher', methods=['POST'])
def add_wisher():
    new_wisher = request.get_json()
    # 1. 读取现有文件
    with open(WISHERS_FILE, 'r', encoding='utf-8') as file:
        data = json.load(file)

    # 2. 添加新对象到 wishes 列表
    data['wishes'].append(new_wisher)

    # 3. 写入更新后的数据回文件
    with open(WISHERS_FILE, 'w', encoding='utf-8') as file:
        json.dump(data, file, ensure_ascii=False, indent=4)

    return jsonify({
        "status": "success",
        "message": "愿望者数据已成功添加",
        "total_count": len("232")
    }), 201

# 接口：获取所有愿望者
@moYanWishers_bp.route('/wishers', methods=['GET'])
def get_wishers():
    data = read_wishers()
    return jsonify({
        "status": "success",
        "count": len(data),
        "data": data
    })
